//
//  UserDao.m
//  eyr
//
//  Created by Tor Gjøsæter on 4/25/12.
//  Copyright (c) 2012 University of Bergen. All rights reserved.
//

#import "UserDao.h"
#import "User+DefaultData.h"
#import "User+Create.h"
#include <CoreData/CoreData.h>

@implementation UserDao

@synthesize userDataBase = _userDataBase;

- (id) initWithDataBase:(NSString *)fileUrl{

    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    //this url gets me the documents directory
    url = [url URLByAppendingPathComponent:@"Default user database"]; //
    self.userDataBase = [[UIManagedDocument alloc] initWithFileURL:url];    
    return self;
}

- (void) addUserToDocument:(NSString *) name{
    UserDao *ud = [UserDao sharedSingleton];
    dispatch_queue_t fetchQ = dispatch_queue_create("Default user database", NULL);
    dispatch_async(fetchQ, ^{
        //The document context is not thread safe, performblock makes sure it runs on its (safe) thread
        [ud.userDataBase.managedObjectContext performBlock:^{
            [User createUser:name inManagedObjectContext:ud.userDataBase.managedObjectContext];  
        }];
    });
    dispatch_release(fetchQ);
}


- (void) addUser:(NSString *)name{
    //IF its not created we will create it and load it up with data
    UserDao *ud = [UserDao sharedSingleton];   
    //This is if the document does not exist
    if(![[NSFileManager defaultManager] fileExistsAtPath:[self.userDataBase.fileURL path]])
    {
        [ud.userDataBase saveToURL:ud.userDataBase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
         {
             [ud addUserToDocument:name];  
         }];
    }else if (ud.userDataBase.documentState == UIDocumentStateClosed){ //THis is if it exists but is closed
        [self.userDataBase openWithCompletionHandler:^(BOOL success){
     [ud addUserToDocument:name];
        }];
    }else if (ud.userDataBase.documentState == UIDocumentStateNormal){
        [ud addUserToDocument:name];  
    }
}

+ (UserDao *) sharedSingleton{
    static dispatch_once_t pred;
    static UserDao *shared = nil;
    
    dispatch_once(&pred, ^{
        NSLog(@"Dispatching");
        shared = [[UserDao alloc] initWithDataBase:@"ikkje brukt lol"];
        [shared setUserDataBase:shared.userDataBase];
    });
    return shared;
}

//Denne er for når me trykker på done
- (void) commitUserDelete{
    
    NSError *error = nil;
    if (![self.userDataBase.managedObjectContext save:&error]){
        NSLog(@"Problem commiting delete");

    }else{
        NSLog(@"Commiting delete");
    }
    
    
}



- (void) deleteUserObject:(NSString *) name{
    NSManagedObjectContext *moc = self.userDataBase.managedObjectContext;
    NSEntityDescription *entityDescription = [NSEntityDescription
                                              entityForName:@"User" inManagedObjectContext:moc];
    NSFetchRequest *request = [NSFetchRequest  fetchRequestWithEntityName:@"User"];
    //NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    [request setEntity:entityDescription];
    
    NSString *query = [NSString stringWithFormat:@"(name LIKE[c] '%@')", name];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:query];
    [request setPredicate:predicate];
    
    NSError *error = nil;
    NSArray *array = [moc executeFetchRequest:request error:&error];
    
    if (array != nil) {
        
        if([[array objectAtIndex:0] isKindOfClass:[User class]]){
             User *myUser = [array objectAtIndex:0];
            [moc deleteObject:myUser];
        }
   
    }
    else {
        NSLog(@"We have an error lululu");
    }
    //Fetch the user managed object
    
    //Cascading delete
    
   
    
 
}

- (void) loadTestBrukerDataIntoDocument:(UIManagedDocument *) document{
    dispatch_queue_t fetchQ = dispatch_queue_create("Default user database", NULL);
    dispatch_async(fetchQ, ^{
        //The document context is not thread safe, performblock makes sure it runs on its (safe) thread
        [document.managedObjectContext performBlock:^{
            [User userWithDefaultData:document.managedObjectContext];  
      }];      
    });
    dispatch_release(fetchQ);    
}



- (void) addTestBruker{
    
    UserDao *ud = [UserDao sharedSingleton];   

    if(![[NSFileManager defaultManager] fileExistsAtPath:[self.userDataBase.fileURL path]])
    {
        [ud.userDataBase saveToURL:self.userDataBase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
         {
             [ud loadTestBrukerDataIntoDocument:ud.userDataBase];
             
         }];
    }else if (ud.userDataBase.documentState == UIDocumentStateClosed){ //THis is if it exists but is closed
        [self.userDataBase openWithCompletionHandler:^(BOOL success){
            [ud loadTestBrukerDataIntoDocument:ud.userDataBase];     
        }];
    }else if (ud.userDataBase.documentState == UIDocumentStateNormal){ 
        [ud loadTestBrukerDataIntoDocument:ud.userDataBase];        
    }
}

- (void) setUserDataBase:(UIManagedDocument *) userDataBase{
    if(_userDataBase != userDataBase){
        _userDataBase = userDataBase;
    //    [self addTestBruker];
    }
}

@end
